package Test;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import weaver.conn.RecordSet;
import weaver.docs.category.SecCategoryComInfo;
import weaver.docs.docs.*;
import weaver.docs.webservices.DocAttachment;
import weaver.docs.webservices.DocInfo;
import weaver.docs.webservices.DocServiceImpl;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.workflow.request.RequestDoc;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.Key;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.compile;

/**
 * @Title: ecology-9-demo
 * @Company: 泛微软件
 * @author: weaver.Dusongsong
 * @version: 1.0
 * @CreateDate: 2020-08-18
 * @Description: ${description}
 * @ModifyLog:
 **/

public class test01 {

    public static void main(String[] args) {
       String str = "";
       double num = Util.getDoubleValue(str, 0);
        System.out.println( num);
        System.out.println(roundToTwoDecimals(num));
    }
    public static double roundToTwoDecimals(double value) {
//        if (value == 0) {
//            return 0;
//        }
        return new BigDecimal(Double.toString(value)).setScale(2, RoundingMode.HALF_UP).doubleValue();
    }
    public static String des3Decode0(String str) {
        String deString = null;
        byte[] test1 = Base64.decodeBase64(str.getBytes());
        System.out.println("28" + test1);
        try {
            //CBC 解密
            byte[] str1 = des3DecodeCBC0(test1);
            deString = new String(str1, "UTF-8");
            System.out.println(deString);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return deString;
    }

    /**
     * @param data 解密短token
     * @return
     * @throws Exception
     */
    public static byte[] des3DecodeCBC0(byte[] data) throws Exception {
        byte[] key0 = "0okm9ijn8uhb7ygv6tfc5rdx".getBytes("UTF-8");
        byte[] keyiv0 = "sin0opec".getBytes("UTF-8");
        Key deskey = null;
        DESedeKeySpec spec = new DESedeKeySpec(key0);
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
        deskey = keyfactory.generateSecret(spec);
        Cipher cipher = Cipher.getInstance("DESede" + "/CBC/PKCS5Padding");
        IvParameterSpec ips = new IvParameterSpec(keyiv0);
        cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
        System.out.println("dddddd" + data.length);
        byte[] bOut = cipher.doFinal(data);
        return bOut;

    }


    // 使用Apache Commons Codec直接生成MD5哈希
    private static String generateMD5(String input) {
        return DigestUtils.md5Hex(input).toUpperCase();
    }

    public static long getDiffMinute(String begintime, String endtime) {
        Date data1 = DateUtil.parse(begintime);
        Date date2 = DateUtil.parse(endtime);
        return DateUtil.between(data1, date2, DateUnit.SECOND);
    }

    private static LocalDate getQuarterStartDate(LocalDate date) {
        int monthValue = date.getMonthValue();
        int year = date.getYear();
        int quarterStartMonth = (monthValue - 1) / 3 * 3 + 1;
        return LocalDate.of(year, quarterStartMonth, 1);
    }

    private static LocalDate getQuarterEndDate(LocalDate date) {
        LocalDate quarterStart = getQuarterStartDate(date);
        LocalDate quarterEnd = quarterStart.plusMonths(3).minusDays(1);
        // Adjust for February in a leap year
        if (quarterEnd.getMonth() == java.time.Month.FEBRUARY && quarterEnd.getDayOfMonth() > 28) {
            quarterEnd = quarterEnd.minusDays(1);
        }
        return quarterEnd;
    }

    //获取时间戳
    public static String getTimestamp() {
        return String.format("%015d", System.currentTimeMillis());
    }

    public static boolean isJSONObject(String str) {
        boolean flag = true;
        try {
            JSONObject.parseObject(str);
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    private static String removeHtml(String str) {
        String temp = "";
        while (str.indexOf("<") >= 0) {
            int index = str.indexOf("<");
            temp += str.substring(0, index);
            str = str.substring(index + 1);
            index = str.indexOf(">");
            str = str.substring(index + 1);
        }
        temp += str;
        if (temp != null) {
            Pattern p = compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(temp);
            temp = m.replaceAll("");
        }
        return temp;
    }

    public static int compareToYearMonth(String yearMonth1, String yearMonth2) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            Date date1 = sdf.parse(yearMonth1);
            Date date2 = sdf.parse(yearMonth2);
            int result = date1.compareTo(date2);
            if (result < 0) {
                System.out.println("第一个年月早于第二个年月");
            } else if (result > 0) {
                System.out.println("第一个年月晚于第二个年月");
            } else {
                System.out.println("两个年月相等");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    private static byte[] base64DecodeChars = new byte[]{-1, -1, -1, -1, -1,
            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
            -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59,
            60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
            10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1,
            -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
            38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1,
            -1, -1};

    /**
     * 解密
     *
     * @param str
     * @return
     */
    public static String decode(String str) {
        byte[] data = str.getBytes();
        int len = data.length;
        ByteArrayOutputStream buf = new ByteArrayOutputStream(len);
        int i = 0;
        int b1, b2, b3, b4;

        while (i < len) {
            do {
                b1 = base64DecodeChars[data[i++]];
            } while (i < len && b1 == -1);
            if (b1 == -1) {
                break;
            }

            do {
                b2 = base64DecodeChars[data[i++]];
            } while (i < len && b2 == -1);
            if (b2 == -1) {
                break;
            }
            buf.write((int) ((b1 << 2) | ((b2 & 0x30) >>> 4)));

            do {
                b3 = data[i++];
                if (b3 == 61) {
                    return new String(buf.toByteArray());
                }
                b3 = base64DecodeChars[b3];
            } while (i < len && b3 == -1);
            if (b3 == -1) {
                break;
            }
            buf.write((int) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));

            do {
                b4 = data[i++];
                if (b4 == 61) {
                    return new String(buf.toByteArray());
                }
                b4 = base64DecodeChars[b4];
            } while (i < len && b4 == -1);
            if (b4 == -1) {
                break;
            }
            buf.write((int) (((b3 & 0x03) << 6) | b4));
        }
        return new String(buf.toByteArray());
    }


    public static String sendOkHttpReq(String itemNumber) {
        String result = "";
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .build();
            MediaType mediaType = MediaType.parse("text/plain");
            RequestBody body = RequestBody.create(mediaType, "");
            Request request = new Request.Builder()
                    .url("http://10.196.80.148:8012/ExternalData/getPdf?itemNumber=" + itemNumber)
                    .get()
                    .build();
            Response response = client.newCall(request).execute();
            System.out.println("response" + response);
            result = Util.null2String(response.body().string());
        } catch (Exception e) {
            System.out.println("接口异常！！");
        }
        return result;
    }

    /**
     * 更新主表表单信息
     */
    public static String updateMainData(String tablename, String requestid, Map<String, Object> map) {

        //遍历数据 进行update
        String updatesql = "update " + tablename + " set ";
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            if ("null".equals(map.get(key))) {
                updatesql += key + "=" + map.get(key).toString() + ",";
            } else {
                updatesql += key + "='" + map.get(key).toString() + "',";
            }
        }
        if (updatesql.endsWith(",")) {
            updatesql = updatesql.substring(0, updatesql.length() - 1);
            updatesql += " where requestid=" + requestid;
        }
        return updatesql;
    }

    // f点型相加
    public static String fAdd(String a, String b) {
        a = isZero(a);
        b = isZero(b);
        BigDecimal bg1 = new BigDecimal(a);
        BigDecimal bg2 = new BigDecimal(b);

        BigDecimal bd = bg1.add(bg2);

        return bd.toString();
    }

    // f点型相减
    public static String fSubtract(String a, String b) {
        a = isZero(a);
        b = isZero(b);
        BigDecimal bg1 = new BigDecimal(a);
        BigDecimal bg2 = new BigDecimal(b);
        BigDecimal bd = bg1.subtract(bg2);
        return bd.toString();
    }

    // 除法保留2位小数 四舍五入
    public static String fDivide(String a, String b) {
        a = isZero(a);
        b = isZero(b);
        BigDecimal bg1 = new BigDecimal(a);
        BigDecimal bg2 = new BigDecimal(b);
        BigDecimal bd = bg1.divide(bg2, 2, BigDecimal.ROUND_HALF_UP);
        return bd.toString();
    }

    // 乘法保留小数位 四舍五入
    public static String fMultiply(String a, String b) {
        a = isZero(a);
        b = isZero(b);
        BigDecimal bg1 = new BigDecimal(a);
        BigDecimal bg2 = new BigDecimal(b);
        BigDecimal bd = bg1.multiply(bg2).setScale(2, BigDecimal.ROUND_HALF_UP);
        return bd.toString();
    }

    // 大小比较 -1 0 1
    public static int fCompare(String a, String b) {
        a = isZero(a);
        b = isZero(b);
        BigDecimal bg1 = new BigDecimal(a);
        BigDecimal bg2 = new BigDecimal(b);
        return bg1.compareTo(bg2);
    }

    // 取绝对值
    public static String fabs(String a) {
        a = isZero(a);
        BigDecimal bg1 = new BigDecimal(a);
        return bg1.abs().toString();
    }

    //零判断
    public static String isZero(String a) {
        if ("".equals(a)) {
            a = "0";
        }
        return a;
    }


    public static String secondConvertHourMinSecond(Long second) {
        String str = "00时00分00秒";
        if (second == null || second < 0) {
            return str;
        }

        // 得到小时
        long h = second / 3600;
        str = h > 0 ? ((h < 10 ? ("0" + h) : h) + ":") : "00h";

        // 得到分钟
        long m = (second % 3600) / 60;
        str += (m < 10 ? ("0" + m) : m) + "m";

        //得到剩余秒
        long s = second % 60;
        str += (s < 10 ? ("0" + s) : s) + "s";
        return str;
    }

    public static String stripHtml(String content) {
        content = content.replaceAll("\\n", "");
        // <p>段落替换为换行
        content = content.replaceAll("<p .*?>", "");
        // <br><br/>替换为换行
        content = content.replaceAll("<br\\s*/?>", "");
        // 去掉其它的<>之间的东西
        content = content.replaceAll("\\<.*?>", "");
        return content;
    }

    /**
     * 根据时间 和时间格式 校验是否正确
     *
     * @param length 校验的长度
     * @param sDate  校验的日期
     * @param format 校验的格式
     * @return
     */
    public static boolean isLegalDate(int length, String sDate, String format) {
        int legalLen = length;
        if ((sDate == null) || (sDate.length() != legalLen)) {
            return false;
        }
        DateFormat formatter = new SimpleDateFormat(format);
        try {
            Date date = formatter.parse(sDate);
            return sDate.equals(formatter.format(date));
        } catch (Exception e) {
            return false;
        }
    }

    private static long secCountDown(long midTime) {
        long second = 0;
        while (midTime > 0) {
            midTime--;
            second = midTime % 60;
            System.out.println("还剩" + second + "秒");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return second;
    }

    /**
     * 存储为文档
     *
     * @param workflowid1
     * @param secid         目录
     * @param user
     * @param uploadField   附件id
     * @param ip
     * @param imagefilename 文档名称
     * @return
     */
    private static int transForDoc(String workflowid1, int secid, User user, String uploadField, String ip, String imagefilename) {
        String filename = "";
        DocExtUtil docExtUtil = new DocExtUtil();
        try {
            SecCategoryComInfo scc = new SecCategoryComInfo();
            DocComInfo dc = new DocComInfo();
            DocManager dm = new DocManager();
            DocViewer dv = new DocViewer();
            DocImageManager imgManger = new DocImageManager();
            int mainId = -1;
            int subId = -1;
            int secId = secid;

            String docSubject = "";
            String docContent = "";
            int workflowid = Util.getIntValue(workflowid1, 0);

            String isWorkflowDraft = "0";
            if (workflowid > 0) {
                RequestDoc requestDoc = new RequestDoc();
                ArrayList docFiledList = requestDoc.getDocFiled("" + workflowid);
                if (docFiledList != null && docFiledList.size() > 6) {
                    isWorkflowDraft = "" + docFiledList.get(6);
                }
            }
            String docStatus = "1";
            if ("1".equals(isWorkflowDraft)) {
                docStatus = "9";
            }
            RecordSet rs = new RecordSet();
            int docId = dm.getNextDocId(rs);
            String imageId = uploadField;
            if (imageId == null) {
                return -1;
            }

            filename = imagefilename;
            String ext = "";
            imgManger.resetParameter();
            docSubject = filename.substring(0, filename.lastIndexOf("."));
            ;
            imgManger.setImagefilename(filename);
            ext = docExtUtil.getFileExt(filename);

            if (ext.equalsIgnoreCase("doc")) {
                imgManger.setDocfiletype("3");
            } else if (ext.equalsIgnoreCase("xls")) {
                imgManger.setDocfiletype("4");
            } else if (ext.equalsIgnoreCase("ppt")) {
                imgManger.setDocfiletype("5");
            } else if (ext.equalsIgnoreCase("wps")) {
                imgManger.setDocfiletype("6");
            } else if (ext.equalsIgnoreCase("docx")) {
                imgManger.setDocfiletype("7");
            } else if (ext.equalsIgnoreCase("xlsx")) {
                imgManger.setDocfiletype("8");
            } else if (ext.equalsIgnoreCase("pptx")) {
                imgManger.setDocfiletype("9");
            } else if (ext.equalsIgnoreCase("et")) {
                imgManger.setDocfiletype("10");
            } else {
                imgManger.setDocfiletype("2");
            }
            imgManger.setDocid(docId);
            imgManger.setImagefileid(Util.getIntValue(imageId, 0));
            imgManger.setIsextfile("1");
            imgManger.AddDocImageInfo();
            String date = "";
            String time = "";
            date = TimeUtil.getCurrentDateString();
            time = TimeUtil.getOnlyCurrentTimeString();

            dm.setId(docId);
            dm.setMaincategory(mainId);
            dm.setSubcategory(subId);
            dm.setSeccategory(secId);
            dm.setLanguageid(user.getLanguage());
            dm.setDoccontent(docContent);
            //dm.setDocstatus("1");
            dm.setDocstatus(docStatus);
            dm.setDocsubject(docSubject);
            dm.setDoccreaterid(user.getUID());
            dm.setDocCreaterType(user.getLogintype());
            dm.setUsertype(user.getLogintype());
            dm.setOwnerid(user.getUID());
            dm.setOwnerType(user.getLogintype());
            dm.setDoclastmoduserid(user.getUID());
            dm.setDocLastModUserType(user.getLogintype());
            dm.setDoccreatedate(date);
            dm.setDoclastmoddate(date);
            dm.setDoccreatetime(time);
            dm.setDoclastmodtime(time);
            dm.setDoclangurage(user.getLanguage());
            dm.setKeyword(docSubject);
            dm.setIsapprover("0");
            dm.setIsreply("");
            dm.setDocdepartmentid(user.getUserDepartment());
            dm.setDocreplyable("1");
            dm.setAccessorycount(1);
            dm.setParentids("" + docId);
            dm.setOrderable("" + scc.getSecOrderable(secId));
            dm.setClientAddress(ip);// added by xwj for td2034
            // on 2005-05-27
            dm.setUserid(user.getUID()); // added by xwj for td2034 on
            // 2005-05-27
            DocCoder docCoder = new DocCoder();
            dm.setDocCode(docCoder.getDocCoder("" + secId));
            dm.setDocEditionId(dm.getNextEditionId(rs));
            dm.setDocEdition(1);

            dm.AddDocInfo();
            // set share
//            dm.AddShareInfo();
            dm.setAboutCreaterShare(String.valueOf(secId));
            dc.addDocInfoCache("" + docId);
            dv.setDocShareByDoc("" + docId);

            return docId;
        } catch (Exception ex) {
            return -1;
        }
    }

    private static String stichString(Object... values) {
        String str = "";
        Object[] localValues = new Object[values.length];
        System.arraycopy(values, 0, localValues, 0, values.length);
        for (Object obj : localValues) {
            str += str == "" ? (String) obj : "," + obj;

        }
        return str;
    }


    /*
     * 将时间戳转换为时间
     */
    public static String stampToDate(Long systemdate) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(systemdate);
        String res = simpleDateFormat.format(date);
        return res;
    }

    /*
     * 将时间转换为时间戳
     */
    public static String dateToStamp(String s) {
        String res = "";
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = simpleDateFormat.parse(s);
            long ts = date.getTime();
            res = String.valueOf(ts);
        } catch (ParseException e) {
            e.getErrorOffset();
        }
        return res;
    }

    private static String autoGenericCode(String code, int num) {
        String result = "";
        result = String.format("%0" + num + "d", Integer.parseInt(code) + 1);
        return result;
    }

    public static String equestStr(String str1, String str2) {
        StringBuilder sb = new StringBuilder();
        String[] strings = str1.split(",");
        for (String s : strings) {
            if (!str2.contains(s)) {
                sb.append(s + ",");
            }
        }
        String str = sb.substring(0, sb.length() - 1).toString();
        return str;
    }

    public static int getEquestStr(String str1, String str2) {
        StringBuilder sb = new StringBuilder();
        int count = 0;
        String[] strings = str1.split(",");
        for (String s : strings) {
            if (str2.contains(s)) {
                count++;
            }
        }
        return count;
    }


    //创建文档
    public static int createDoc(String userid, String content, String filetype, String rawFileName) {
        BaseBean log = new BaseBean();
        int docid = -1;
        DocServiceImpl docserviceimpl = new DocServiceImpl();
        String docsubject = ""; //文档标题
        String keyword = ""; //文档内容
        try {
            DocAttachment[] docattachment = new DocAttachment[1];
            if (rawFileName.lastIndexOf(".") > -1) {
                filetype = rawFileName.substring(rawFileName.lastIndexOf(".") + 1);
            }
            DocAttachment da = new DocAttachment();
            da.setFilename(rawFileName);//附件标题
            da.setFilecontent(content); //附件内容
            da.setFiletype(filetype); //imagefiletype
            da.setImagefilename(rawFileName);// 附件标题
            da.setIszip(1);//是否压缩
            da.setIsAesEncrype(0);//是否加密
            da.setAesCode("0");
            da.setIsextfile("1"); //附件是否是office类型

            if (filetype.equalsIgnoreCase("doc")) {
                da.setDocfiletype("3");
            } else if (filetype.equalsIgnoreCase("xls")) {
                da.setDocfiletype("4");
            } else if (filetype.equalsIgnoreCase("ppt")) {
                da.setDocfiletype("5");
            } else if (filetype.equalsIgnoreCase("wps")) {
                da.setDocfiletype("6");
            } else if (filetype.equalsIgnoreCase("docx")) {
                da.setDocfiletype("7");
            } else if (filetype.equalsIgnoreCase("xlsx")) {
                da.setDocfiletype("8");
            } else if (filetype.equalsIgnoreCase("pptx")) {
                da.setDocfiletype("9");
            } else {
                da.setDocfiletype("2");
            }
            docattachment[0] = da;
            docsubject = rawFileName;
            keyword = rawFileName;

            DocInfo doc = new DocInfo(); //创建文档
            doc.setMaincategory(0);//主目录id
            doc.setSubcategory(0);//分目录id
            doc.setSeccategory(123);//子目录id

            doc.setDocSubject(docsubject);//标题
            doc.setDoccontent("");//文档内容
            doc.setKeyword(keyword);
            doc.setAttachments(docattachment);
            log.writeLog("userid:" + userid);
            if (!"".equals(userid)) {
                User user = new User(weaver.general.Util.getIntValue(userid));
                docid = docserviceimpl.createDocByUser(doc, user);
                log.writeLog("docid:" + docid);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.writeLog("e:" + e);
        }
        return docid;
    }
}
